﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Framework.LinkTrackingLog.AI_Deepseek
{
    /// <summary>
    /// API执行时间监控过滤器
    /// 职责：监控Controller Action方法的执行时间
    /// </summary>
    public class ApiExecutionTimeFilter : IAsyncActionFilter
    {
        private readonly ILogger<ApiExecutionTimeFilter> _logger;
        private readonly IMethodMonitoringService _monitoringService;

        /// <summary>
        /// 构造函数注入依赖项
        /// </summary>
        public ApiExecutionTimeFilter(
            ILogger<ApiExecutionTimeFilter> logger,
            IMethodMonitoringService monitoringService)
        {
            _logger = logger;
            _monitoringService = monitoringService;
        }

        /// <summary>
        /// Action执行拦截方法
        /// </summary>
        public async Task OnActionExecutionAsync(
            ActionExecutingContext context,
            ActionExecutionDelegate next)
        {
            // 检查Action是否标记了[NoMonitor]特性
            if (context.ActionDescriptor.EndpointMetadata.Any(m => m is NoMonitorAttribute))
            {
                await next(); // 如果标记则不监控，直接执行
                return;
            }

            // 构建方法名称：ControllerName.ActionName
            var methodName = $"{context.Controller.GetType().Name}.{context.ActionDescriptor.DisplayName}";

            // 开始监控，using确保监控范围正确结束
            using (_monitoringService.BeginMonitor(methodName))
            {
                await next(); // 执行实际Action方法
            }
            // using块结束时自动记录执行时间
        }
    }
}
